package main

import "fmt"

// 使用通道并发访问对象

type Person struct {
	name   string
	salary float64
	chFunc chan func()
}

func (p *Person) backend() {
	for f := range p.chFunc {
		f()
	}
}

// 工厂函数, 创建结构体实例的同时开启对应协程
func NewPerson(name string, salary float64) *Person {
	p := &Person{name, salary, make(chan func())}
	go p.backend()
	return p
}

func (p *Person) SetSalary(s float64) {
	p.chFunc <- func() {
		p.salary = s
	}
}

func (p *Person) Salary() float64 {
	chSal := make(chan float64)

	p.chFunc <- func() {
		chSal <- p.salary
		close(chSal)
	}
	return <-chSal
}

func (p *Person) String() string {
	return fmt.Sprintf("Person name: %s - salary: %0.2f", p.name, p.Salary())
}

func main() {
	ht := NewPerson("hutao", 3600.6)
	fmt.Println(ht)
	ht.SetSalary(7201.3)
	fmt.Println("涨工资咯")
	fmt.Println(ht)

}
